<?php
/**
* d17操作
*/
class d17
{
    //**** 定义私有变量 ****//

        // 用户信息相关
        private $userName;          // 用户账号
        private $password;          // 用户密码
        private $userCookies;       // 登录Cookies
        private $status = 0;        // 状态

        // 定义错误信息
        private $errorMsg;          // 错误信息

        // 系统选项相关
        private $options = array(
            'recordsFile' => './userRecords.json',   // 记录用户信息的文件
        );

        //  新闻默认选填参数
        private $postOptions = array(
            'd17_form_token_'   => true,     // 
            'title'      => true,     // 新闻标题(完整)
        	'titlePicPath'=>true,  
            'newssummary'     => true,       // 新闻简介
            'body'      => true,      // 新闻内内容
        );
        
        //  文章默认选填参数
        private $postOptionss = array(
        		'd17_form_token_'=> true,
				'categoryId' =>148628,
				'standardAttrs'  => '', 
				'inputAttrs'=>true,
				'standardAttrsStr'  => '', 
				'inputAttrsStr'=>true,
				'customAttrs'  => '', 
				'productImage'=>true,
				'keywords'  => '', 
				'priceLadder'  => '', 
				'minPurchaseNum'=>0,
				'standardAttrSize'=>2,
				'subject'=>true,
				'detail'=>true,
				'online1'=>"",
        		'online'=>"",
				'offlineDate'  => '', 
				'price'=>0,
				'priceUnit'  => '', 
				'min_purchase_type'=>0,
        		'min_purchase_type2'=>"",
        );
     
    /**
     * 初始化函数
     * @param string $userName    用户账号
     * @param string $password    用户密码
     * @param string $userCookies 登录Cookies
     * @param array  $options     配置选项信息
     */
    function __construct($userName, $password, $userCookies = null, $options = array())
    {  	
        $this->userName = $userName;  // 保存用户账号
        $this->password = $password;  // 保存用户密码

        // 识别并保存配置选项
        foreach ($options as $optKey => $optValue)
            $this->options[$optKey] = $optValue;

        // 检查保存用户信息的文件
        file_exists($this->options['recordsFile']) ?: file_put_contents($this->options['recordsFile'], '{}');

        // 设置并保存Cookies
        if(!$userCookies){
            $userRecords = json_decode(file_get_contents($this->options['recordsFile']), true);
            if(!empty($userRecords[$this->userName]['Cookies']))
                $userCookies = $userRecords[$this->userName]['Cookies'];
        }

        $this->setCookie($userCookies) ?: $this->errorMsg = 'NotLogin';
    }

    /**
     * 获取上次操作的错误信息
     * @return string 错误信息描述
     */
    public function getErrorMsg()
    {
        return $this->errorMsg;
    }

    /**
     * 设置并验证用户Cookies
     * @param string $cookies 用户Cookies
     */
    public function setCookie($cookies = null)
    {
        // 验证登录的地址
        $url = 'http://www.d17.cc/d17/user/main';

        // 提交请求
        $retHtml = Get_Web_Contents($url, 'GET', '',$cookies);
        
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错';
            return false;
        }

        // 判断是否已经登录
        $regEx = '#<input[^>]+name="(?<name>[^"]+)"[^>]+placeholder="(?<type>[^"]+)"/>#';
        if(!preg_match_all($regEx, $retHtml['Body'], $formInfo)) {
         $this->userCookies = $cookies;
            $this->status      = 1;
            return true;
        } else {
            $this->status   = 0;
            $this->errorMsg = '账号未登录';
            return false;
        }
    }

    /**
     * 保存用户的Cookies
     */
    public function saveCookie()
    {
        if($this->status <= 0) {
            $this->errorMsg = '登录状态不正确';
            return false;
        }
        $userRecords = json_decode(file_get_contents($this->options['recordsFile']), true);
        $userRecords[$this->userName]['Cookies'] = $this->userCookies;
        if(!file_put_contents($this->options['recordsFile'], json_encode($userRecords))){
            $this->errorMsg = '保存到json文件失败';
            return false;
        }
        return true;
    }

    /**
     * 用户账号登录
     * @param  string $userName 需要登录的用户账号
     * @param  string $password 需要登录的用户密码
     * @return mixed            登录成功返回用户Cookies 失败返回 false
     */
    public function userLogin($userName = null, $password = null)
    {
        // 设置账号密码
        $userName ?: $userName = $this->userName;
        $password ?: $password = $this->password;

        // 登录提交的地址
        $url = 'http://www.d17.cc/d17/pages/user/login.jsp';

        // 获取登录表单信息
        $retHtml = Get_Web_Contents($url);
        if(empty($retHtml['Body'])){
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }

        // 匹配表单字段名
        $regEx = '#<input[^>]+name="(?<name>[^"]+)"[^>]+placeholder="(?<type>[^"]+)"/>#';
        if(!preg_match_all($regEx, $retHtml['Body'], $formInfo)) {
            $this->errorMsg = '匹配表单字段名失败.';
            return false;
        }

        // 校验码
        $regEx = '#name="d17_form_token_" value="(?<val>[^"]+)"#';
        if(!preg_match($regEx, $retHtml['Body'], $formToken)){
        	$this->errorMsg = '提取表单校验时出错.';
        	return false;
        }
        // 生成表单信息
        $data = 'd17_form_token_='.$formToken['val'].'&';
        foreach ($formInfo['type'] as $key => $type) {
            switch ($type) {
                case '用户名':
                    $data.= "{$formInfo['name'][$key]}={$userName}&";
                    break;
                case '密码':
                    $data.= "{$formInfo['name'][$key]}={$password}&";
                    break;
                default:
                    # code...
                    break;
            }
        }
        $data.= 'remember=true';

       
        // 提交登录数据
        $URL='http://www.d17.cc/d17/user/login';
        $retHtml = Get_Web_Contents($URL, 'POST', $data ,$retHtml['Cookies']);
        
       
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }
       
        // 判断登录没有
        $json= $retHtml['Body'];
        $yes=json_decode($json, true)["success"];
        if(empty($yes)){
            $this->errorMsg = "登录失败了";
            return false;
        }

        $this->userCookies = $retHtml['Cookies'];
        $this->status      = 1;
        return $retHtml['Cookies'];
    }

    /**
     * 发布新闻
     * @param  string  $title    文章标题
     * @param  string  $body     文章内容
     * @param  integer $classID  分类ID(全站)
     * @param  integer $columnID 栏目ID(本站)
     * @param  array   $options  其他选项
     * @return [type]           [description]
     */
    public function postAddnew($title,$userList, $options)
    {
    	
    	$markName = $userList['mark'];
    	$postArr  = getDalArticle($markName);
    	$postInfo = $postArr['0'];
    	
    	// 字符串替换
    	$postInfonew['body'] = postBodyReplace($postInfo['body'], $userList['hosType'], $title);
    	
    	// 末尾追加发布时间
    	$postInfonew['body'].= '<p>'.date('YmdHis').'</p>';
    	
    	//获取新闻的简介
    	$newssummary=postnewssummary($postInfonew['body']);
    	
    	
        $url = 'http://www.d17.cc/d17/news/toAddNewsPage';

        // 获取页面内容用来提取表单字段名
        $retHtml = Get_Web_Contents($url, 'GET', '', $this->userCookies);
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }
        // 获取表单正文
        $regEx = '#<form[^>]+id="newsForm">(?<form>.*?)</form>#s';
        if(!preg_match($regEx, $retHtml['Body'], $formBody)){
            // 先检查是否频繁
            $this->errorMsg = '提取表单正文时失败.';
            if(stripos($retHtml['Body'], '休息一会')){
                $this->errorMsg = '操作频繁';
            }
            return false;
        }

        // 获取表单字段
        $regEx = '#name="(?<name>[^"]+)"#';
        if(!preg_match_all($regEx, $formBody['form'], $formList)){
            $this->errorMsg = '提取表单字段列表时出错.';
            return false;
        }
        $formList = $formList['name'];
        
        // 获取 验证 token 的值
        $regEx = '#name="d17_form_token_" value="(?<val>[^"]+)"#';
        if(!preg_match($regEx, $formBody['form'], $formToken)){
            $this->errorMsg = '提取表单校验时出错.';
            return false;
        }

        // 修改值
           $this->postOptions["titlePicPath"] = $options["titlePicPath"];
           $this->postOptions['title']      = $title;      // 文章标题
           $this->postOptions['newssummary']      = $newssummary;      // 文章简介
           $this->postOptions['body']       = $postInfonew['body'];       // 文章内容
           $this->postOptions['d17_form_token_']     = $formToken['val'];      // 效验码

        // 重新整理值关系
        $i = 0;$postData = array();
        foreach ($this->postOptions as $key => $value) {
            $name = $formList[$i++];
            $postData[$name] = $value;
        }
     
        $URL="http://www.d17.cc/d17/news/addNews";
        $retHtml = Get_Web_Contents($URL, 'POST', http_build_query($postData), $this->userCookies);
       
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }

       // 判断是否成功
        $json= $retHtml['Body'];
        $yes=json_decode($json, true)["success"];
        if(empty($yes)){
        	$this->postAddnew($title,$userList, $options);
            $this->errorMsg = json_decode($json, true)["message"];
            return false;
        }else{
        	return true;
        }
    
    }
    
    
    
    
    /**
     * 发布文章
     * @param  string  $title    文章标题
     * @param  string  $body     文章内容
     * @param  integer $classID  分类ID(全站)
     * @param  integer $columnID 栏目ID(本站)
     * @param  array   $options  其他选项
     * @return [type]           [description]
     */
    public function postAddproduct($title, $userList, $options)
    {
    	$markName = $userList['mark'];
    	$postArr  = getDalArticle($markName);
    	$postInfo = $postArr['0'];

    	// 字符串替换
    	
    	$postInfoproduct['body'] = postBodyReplace($postInfo['body'], $userList['hosType'], $title);
    	// 末尾追加发布时间
    	
    	$postInfoproduct['body'].= date('YmdHis');
    	
    	$url = 'http://www.d17.cc/d17/product/publishProductPage?catId=148628';
    
    	// 获取页面内容用来提取表单字段名
    	$retHtml = Get_Web_Contents($url, 'GET', '', $this->userCookies);
    	if(isset($retHtml['Error'])) {
    		$this->errorMsg = 'cUrl请求时出错.';
    		return false;
    	}
    	// 获取表单正文
    	$regEx = '#<form[^>]+id="productForm">(?<form>.*?)</form>#s';
    	if(!preg_match($regEx, $retHtml['Body'], $formBody)){
    		// 先检查是否频繁
    		$this->errorMsg = '提取表单正文时失败.';
    		if(stripos($retHtml['Body'], '休息一会')){
    			
    			$this->errorMsg = '操作频繁';
    		}
    		return false;
    	}
    
    	// 获取表单字段
    	$regEx = '#name="(?<name>[^"]+)"#';
    	if(!preg_match_all($regEx, $formBody['form'], $formList)){
    		$this->errorMsg = '提取表单字段列表时出错.';
    		return false;
    	}
    	$formList = $formList['name'];
    
    	// 获取 验证 token 的值
    	$regEx = '#name="d17_form_token_" value="(?<val>[^"]+)"#';
    	if(!preg_match($regEx, $formBody['form'], $formToken)){
    		$this->errorMsg = '提取表单校验时出错.';
    		return false;
    	}
    
    	// 修改值

    	$this->postOptionss["productImage"] = $options["productImage"];
    	$this->postOptionss['inputAttrs']      = '50631:广东';      // 地点
    	$this->postOptionss['inputAttrsStr']      = '所在地:广东';      //地点
    	$this->postOptionss['subject']      = $title;      // 文章标题
    	$this->postOptionss['detail']      = $postInfoproduct['body'];      // 文章内容
    	$this->postOptionss['d17_form_token_']      = $formToken['val'];      // 效验码
    	// 重新整理值关系
    	$i = 0;$postData = array();
    	foreach ($this->postOptionss as $key => $value) {
    		$name = $formList[$i++];
    		$postData[$name] = $value;
    	}

    	$URL="http://www.d17.cc/d17/product/publishProduct";
    	$retHtml = Get_Web_Contents($URL, 'POST', http_build_query($postData), $this->userCookies);
    	if(isset($retHtml['Error'])) {
    		$this->errorMsg = 'cUrl请求时出错.';
    		return false;
    	}  

    	// 判断是否成功
        $json= $retHtml['Body'];
        $yes=json_decode($json, true)["success"];
        if(empty($yes)){
        	$this->postAddproduct($title, $userList, $options);
        }
        
        return true;
    }
    
    /**
     * 获取文章列表
     * @param  integer $page 页码
     * @return array         所有地址
     */
    public function getPostList($list = 1)
    {
    	
    	//获取产品的链接
    	$str_product="";
    	for($i=1; $i<=$list/10; $i++){
	    	$url = "http://www.d17.cc/d17/product/toProductManage/$i";    	
	        // 读取页面内容
	        $retHtml = Get_Web_Contents($url, 'GET', '', $this->userCookies);
	        
	        $retHtml['Body'] = str_ireplace(array("\r\n","\t", "\r","\n"), '', $retHtml['Body']);
	        // 拼接读取地址
	        $regEx = '#name="pidBox" value="(?<val>[^"]+)"#s';
	        if(!preg_match_all($regEx, $retHtml['Body'], $val)){  
	        	$this->errorMsg = '提取a标签列表时出错.';
	        	return false;
	        }
	        $str_product .= implode(",",$val['val']).",";
	        
	        }
	        $str_product = substr($str_product,0,strlen($str_product)-1);
	        $val['val']=explode(",",$str_product);
	        
        
        
        //获取新闻的链接
    	$str_new="";
        for($l=1; $l<=$list/5; $l++){
        $urlnew = "http://www.d17.cc/d17/news/newsList/$l";
       
        // 读取页面内容
        $retHtmlnew = Get_Web_Contents($urlnew, 'GET', '', $this->userCookies);
        
        $retHtmlnew['Body'] = str_ireplace(array("\r\n","\t", "\r","\n"), '', $retHtmlnew['Body']);
        // 拼接读取地址
        $regEx = '#name="pidBox" [^v]+value="(?<val>[^"]+)"#s';
        if(!preg_match_all($regEx, $retHtmlnew['Body'], $valnew)){
        	$this->errorMsg = '提取新闻a标签列表时出错.';
        	return false;
        }
        $str_new .= implode(",",$valnew['val']).",";
        
         }
         $str_new = substr($str_new,0,strlen($str_new)-1);
         $valnew['val']=explode(",",$str_new);
      
         $retList = array();
        // 分割每条记录
        
        foreach ($valnew['val'] as $key => $value) {
        	//新闻web
        	$retList['info'][$key]  = 'http://sznkyy.d17.cc/news/'.$value.'.html';
        	//新闻手机
        	$retList['wap'][$key]   = 'http://m.d17.cc/sznkyy/news/show-'.$value.'.html';
        
        }
       foreach ($val['val'] as $key => $value) {
	        //产品web
	        $retList['site'][$key]  = 'http://sell.d17.cc/show/'.$value.'.html';
	        //产品手机
	        $retList['sitem'][$key] = 'http://m.d17.cc/sell/show-'.$value.'.html';
       }
        return $retList;
       
    }

	//获取发布文章的所有URL 和 标题 列表
	function savePostUrl_Title($userName,$postList,$i){
		
		$saveErro = "";
		$info = $wap = $site = $sitem  = $titleList = array();//初始化

		$info  = $postList['info'];
		$wap   = $postList['wap'];
		$site  = $postList['site'];
		$sitem = $postList['sitem'];
		$len   = count($site);
		
		$url = "http://www.d17.cc/d17/product/toProductManage/{$i}";
		$contents = Get_Web_Contents($url, 'GET', '', $this->userCookies);// 读取页面内容
		if (!$contents['Body']) print_r("{$userName}··· 没有读取到页面内容\n");
		for($j=0; $j<$len; $j++){
			
			$patt = "#{$site[$j]}\" title=\"(.*?)\">#s";
			$res = preg_match($patt,$contents['Body'],$getTitle);
			if (!$res) print_r("{$userName}··· 没有获取到标题\n");
			//获取关键词（标题）
			$titleList[] = trim($getTitle[1]);
			$temp = array($info[$j],$wap[$j],$site[$j],$sitem[$j],trim($getTitle[1]));
			$hash = implode(",",$temp);
			unset($temp);
			$res = file_put_contents(POST_URL_KEY_LIST.$userName.".csv", $hash."\n", FILE_APPEND);
			if (!$res) $saveErro = true;
		}
		$json_titleList = json_encode($titleList); 
		return ($saveErro === true) ? false : $json_titleList;
	}
	
	//单独保存关键词
	function saveKey($userName,$json_titleList){
		$titleList = json_decode($json_titleList,true);
		$str_title = implode(",", $titleList);
		$res = file_put_contents(POST_KEY_LOG."{$userName}_key.csv", $str_title.",", FILE_APPEND);
		return ($res == false) ? false : true;
	}
}







